package controllers.production;

import hprose.HproseClinetService;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import play.Logger;
import utils.convert.Convert;
import utils.logs.LogsUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ning.http.util.Base64;

import component.UserBis;
import constants.APIConstants;
import constants.Constants;
import controllers.common.filter.BaseFilter;

public class ProductionPlanAction extends BaseFilter {
	/**
	 * 生产计划初始化
	* @Title: index 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void index() {
		JSONObject projects = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("isPage", Constants.DATAISPAGE_NO);
		map.put("states", "0,1,2");
		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.PJMSI_GETPROJECT, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		projects = JSONObject.parseObject(res);
		JSONArray arr =projects.getJSONArray("data");
		for (int i = 0; i < arr.size(); i++) {
			JSONObject project = arr.getJSONObject(i);
			project.put("id", project.get("project_id"));
			project.put("value", project.get("project_name"));
		}
		render(projects);
	}
	/**
	 * 获取计划列表
	* @Title: getPlanList 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void getPlanList(){
		JSONObject plans = new JSONObject();
		Map<String, Object> planParams = new HashMap<String, Object>();
		planParams.put("customer_id", UserBis.currUser());
		planParams.put("isPage", Constants.DATAISPAGE_NO);
		planParams.put("start_date", params.get("start_date"));
		planParams.put("end_date", params.get("end_date"));
		planParams.put("plan_name", params.get("plan_name"));
		Object [] arguments = new Object[]{planParams};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_GETPRODUCTIONPLAN, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	/**
	 * 根据项目获取工序
	* @Title: getProcessListByProjectId 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void getProcessListByProjectId(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("project_id", params.get("project_id"));
		Object [] arguments = new Object[]{map};
		String processs = HproseClinetService.synCall(APIConstants.PSMSI_GETPROCESSBYPROJECTID, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String classess= HproseClinetService.synCall(APIConstants.CMI_GETCLASSESLIST, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject processJSON = JSONObject.parseObject(processs);
		JSONObject classessJSON = JSONObject.parseObject(classess);
		JSONArray classessArr = classessJSON.getJSONArray("data");
		JSONArray processArr = processJSON.getJSONArray("data");
		JSONArray columnDs = new JSONArray();
		JSONObject processTitle = new JSONObject();
		processTitle.put("id", "gongxu");
		processTitle.put("header", "工序");
		processTitle.put("fillspace", true);
		columnDs.add(processTitle);
 		for (int i = 0; i < classessArr.size(); i++) {
			JSONObject classes = classessArr.getJSONObject(i);
			JSONObject columnD = new JSONObject();
			columnD.put("id", classes.get("class_id"));
			columnD.put("header", classes.get("class_name"));
			columnD.put("fillspace", true);
			columnD.put("editor", "text");
			columnDs.add(columnD);
		}
 		JSONArray tableBodys = new JSONArray();
		for (int i = 0; i < processArr.size(); i++) {
			JSONObject tableBody = new JSONObject();
			JSONObject process = processArr.getJSONObject(i);
			tableBody.put("gongxu", process.get("process_name")+"/"+process.get("process_id"));
			for (int j = 0; j < columnDs.size(); j++) {
				JSONObject classes = columnDs.getJSONObject(j);
				if(!classes.get("id").equals("gongxu")){
					tableBody.put(classes.getString("id"), "");
				}
			}
			tableBodys.add(tableBody);
		}
		JSONObject json = new JSONObject();
		json.put("tableHead", columnDs);
		json.put("tableBodys", tableBodys);
		renderJSON(json);
	}
	/**
	 * 添加计划
	* @Title: addPlan 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void addPlan(){ 
		JSONObject plans = new JSONObject();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("plan_name", params.get("plan_name"));
		map.put("project_id", params.get("project_id"));
		map.put("plan_start_date", params.get("start_date"));
		map.put("plan_end_date", params.get("end_date"));
		map.put("is_auto", params.get("is_auto"));
		map.put("downtime", params.get("downtime"));
		String tableValues = params.get("tableValues");
		String [] arr = tableValues.substring(0,tableValues.length()-1).split("@");
		JSONArray jsonArr = new JSONArray();
		for (int i = 0; i < arr.length; i++) {
			JSONObject json = JSONObject.parseObject(arr[i]);
			String [] gongxu = json.getString("gongxu").split("/");
			json.remove("gongxu");
			json.remove("id");
			for (String key : json.keySet()) {
				JSONObject newJson = new JSONObject();
				newJson.put("process_id", gongxu[1]);
				newJson.put("classes_id", key);
				newJson.put("yield", json.get(key));
				jsonArr.add(newJson);
			}
		}
		map.put("yieds", jsonArr+"");
		Object [] arguments = new Object[]{map};
		LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "添加生产计划执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		String res = HproseClinetService.synCall(APIConstants.PPMSI_ADDPLAN, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	/**
	 * 生产排配初始化
	* @Title: planDetailIndex 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void planDetailIndex() {
		Map<String, Object> planParams = new HashMap<String, Object>();
		planParams.put("customer_id", UserBis.currUser());
		planParams.put("isPage", "2");
		Object [] arguments = new Object[]{planParams};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_GETPRODUCTIONPLAN, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String res2 = HproseClinetService.synCall(APIConstants.GMI_GETGROUPLIST, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String res3 = HproseClinetService.synCall(APIConstants.MGMI_GETGROUPLIST, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String res4 = HproseClinetService.synCall(APIConstants.TMI_GETTERMINALBYCONDITION, arguments,APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);

		JSONObject plans = JSONObject.parseObject(res);
		JSONObject gourps = JSONObject.parseObject(res2);
		JSONObject machines = JSONObject.parseObject(res3);
		JSONObject terminals = JSONObject.parseObject(res4);
		JSONArray gourpArr = gourps.getJSONArray("data");
		JSONArray machineArr =machines.getJSONArray("data");
		for (int i = 0; i < machineArr.size(); i++) {
			JSONObject machine = machineArr.getJSONObject(i);
			machine.put("id", machine.get("gourp_id"));
			machine.put("value", machine.get("gourp_name"));
		}
		for (int i = 0; i < gourpArr.size(); i++) {
			JSONObject obj = gourpArr.getJSONObject(i);
			obj.put("id", obj.get("gourp_id"));
			obj.put("value", obj.get("gourp_name"));
		}
		
		JSONArray jsonArr = plans.getJSONArray("data");
		 for (int i = 0; i < jsonArr.size(); i++) {
			JSONObject obj = jsonArr.getJSONObject(i);
			obj.put("id", obj.get("plan_id"));
			obj.put("value", obj.get("plan_name"));
		}
		 JSONArray terminalArr = terminals.getJSONArray("data");
		 for (int i = 0; i < terminalArr.size(); i++) {
				JSONObject obj = terminalArr.getJSONObject(i);
				obj.put("id", obj.get("terminal_id"));
				obj.put("value", obj.get("terminal_id"));
				obj.put("checkbox", true);
				obj.put("checked", true);
			}
		render(plans,gourpArr,machineArr,terminalArr);
	}
	/**
	 * 获取排配信息
	* @Title: getPlanDetailList 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void getPlanDetailList(){
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("plan_id", params.get("plan_id"));
		map.put("date", params.get("date"));
		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_GETNOWCUTTERUSEPLANHISTORY, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String res2 = HproseClinetService.synCall(APIConstants.PPMSI_GETPRODUCTIONPLANBYPLANID,  arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		
		// 查询客户刀具库
		Map<String, Object> map2 = new HashMap<String, Object>();
		map2.put("customer_id", UserBis.currUser());
		map2.put("isPage", "2");
		Object [] arguments2 = new Object[]{map2};
		String res3 = HproseClinetService.synCall(APIConstants.CSMI_GETCUTTERSPECS, arguments2, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject plans = new JSONObject();
		if(StringUtils.isNotBlank(res)){
		 plans = JSONObject.parseObject(res);
 		JSONArray planArr = plans.getJSONArray("data");
		JSONObject cutters = JSONObject.parseObject(res3);
		JSONArray cutterArr = cutters.getJSONArray("data");
		// 添加客户规格
		for (int i = 0; i < planArr.size(); i++) {
			JSONObject pla = planArr.getJSONObject(i);
			for (int j = 0; j < cutterArr.size(); j++) {
				JSONObject cutter = cutterArr.getJSONObject(j);
				if(cutter.get("material_id").equals(pla.get("material_id"))){
					pla.put("long_specs_cust", cutter.get("long_specs_cust"));
					break ;
				}
			}
		}
		JSONObject plan = JSONObject.parseObject(res2);
		plans.put("plan_data", plan);
 		renderJSON(plans);
		}
	}
	
	/**
	 * 保存修改
	* @Title: addNowCutterUsePlanHistory 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void addNowCutterUsePlanHistory(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("plan_id", params.get("plan_id"));
		map.put("date", params.get("date"));
		map.put("cutterPlans", params.get("cutterPlans"));
		Object [] arguments = new Object[]{map};
		String res="";
		String batch = params.get("batch");
		// batch == 1   批量保存
		if("1".equals(batch)){
			res = HproseClinetService.synCall(APIConstants.PPMSI_ADDBATCHNEWCUTTERUSEPLANHISTORY, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "生产排配批量保存执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		}else{
			res = HproseClinetService.synCall(APIConstants.PPMSI_ADDNEWCUTTERUSEPLANHISTORY, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "生产排配保存执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		}
		
		JSONObject plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	/**
	 * 立即下发
	* @Title: addPlanDetail 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void addPlanDetail(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("plan_id", params.get("plan_id"));
		map.put("use_date", params.get("date"));
		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_ADDPLANDETAILGOURPS, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "生产排配立即下发执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		JSONObject plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	/**
	 * 完成排配
	* @Title: completeSchedule 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void  completeSchedule(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("plan_id", params.get("plan_id"));
		map.put("use_date", params.get("date"));
		map.put("batch", params.get("batch"));
		map.put("terminal_ids", params.get("terminal_ids"));
		map.put("is_replace", params.get("is_replace"));
		Logger.info(params.get("terminal_ids"));
		Object [] arguments = new Object[]{map};
		LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "生产排配审核下发执行","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		String res = HproseClinetService.synCall(APIConstants.PPMSI_COMPLETESCHEDULE, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	/**
	 * 删除计划 
	* @Title: delPlanById 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author chasel 641243343@qq.com   
	* @throws
	 */
	public static void delPlanById(){
		JSONObject plans = new JSONObject();
		Map<String, Object> planParams = new HashMap<String, Object>();
		planParams.put("customer_id", UserBis.currUser());
		planParams.put("plan_id", params.get("plan_id"));
		Object [] arguments = new Object[]{planParams};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_DELETEPLAN, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	
	public static void updatePlan(){
		Map<String, Object> planParams = new HashMap<String, Object>();
		planParams.put("customer_id", UserBis.currUser());
		planParams.put("jsonArr", params.get("jsonArr"));
		Object [] arguments = new Object[]{planParams};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_UPADATEPLAN, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
	
	/**
	 * 生产实际产能初始化
	* @Title: planActualYieldIndex 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author liqi
	* @throws
	 */
	public static void planActualYieldIndex() {
		Map<String, Object> planParams = new HashMap<String, Object>();
		planParams.put("customer_id", UserBis.currUser());
		planParams.put("isPage", "2");
		Object [] arguments = new Object[]{planParams};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_GETPRODUCTIONPLAN, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject plans = JSONObject.parseObject(res);
		
		JSONArray jsonArr = plans.getJSONArray("data");
		 for (int i = 0; i < jsonArr.size(); i++) {
			JSONObject obj = jsonArr.getJSONObject(i);
			obj.put("id", obj.get("plan_id"));
			obj.put("value", obj.get("plan_name"));
		}
		render(plans);
	}
	
	/**
	 * 获取计划详情
	* @Title: getPlanActualYieldList 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型  Index
	* @author liqi
	* @throws
	 */
	public static void getPlanActualYieldList(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("plan_id", params.get("plan_id"));
		map.put("date", params.get("date"));
		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_GETPLANDETAILS, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		String res2 = HproseClinetService.synCall(APIConstants.PPMSI_GETPRODUCTIONPLANBYPLANID,  arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		
		JSONObject plans = JSONObject.parseObject(res);
		JSONObject plan = JSONObject.parseObject(res2);
		plans.put("plan_data", plan);
 		renderJSON(plans);
	}
	
	/**
	 * 添加实际产能
	* @Title: addProductionPlanActualYield 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param     设定文件 
	* @return void    返回类型 
	* @author liqi
	* @throws
	 */
	public static void addProductionPlanActualYield(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("plan_id", params.get("plan_id"));
		map.put("date", params.get("date"));
		map.put("project_id", params.get("project_id"));
		List data = JSONObject.parseArray(params.get("data"));
		map.put("data", data);
		
		Object [] arguments = new Object[]{map};
		LogsUtils.addLogs(Constants.LOG_TYPE_ADD,Convert.convertToInt(UserBis.currOperatorId(),-1), 1, "执行实际产能添加","success", UserBis.currLoginAccount(), UserBis.currUserName(), UserBis.currUser());
		String res = HproseClinetService.synCall(APIConstants.PPMSI_ADDPRODUCTIONPLANACTUALYIELD, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		JSONObject plans = JSONObject.parseObject(res);
		renderJSON(plans);
	}
	
	/**
	 * 补发生产计划
	 */
	public static void reIssuseSchedule(){
		Map<String, Object> map = new HashMap<String, Object>();
		String customer_id;
		try {
			customer_id = new String(Base64.decode(params.get("customer_id")),"UTF-8");
			map.put("customer_id", customer_id);
			Object [] arguments = new Object[]{map};
			String res = HproseClinetService.synCall(APIConstants.PPMSI_ADDPRODUCTIONPLANACTUALYIELD, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
			JSONObject plans = JSONObject.parseObject(res);
			renderJSON(plans);
		} catch (Exception e) {
			Logger.info(e.getMessage());
		}
	}
	
	public static void getScheduleOutVersionList(){ 
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("customer_id", UserBis.currUser());
		map.put("plan_id", params.get("plan_id"));
		map.put("date", params.get("date"));
		Object [] arguments = new Object[]{map};
		String res = HproseClinetService.synCall(APIConstants.PPMSI_GETSCHEDULEOUTVERSIONLIST, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
		renderJSON(res);
	}
//
//	public static void submitYield() {
//
//		Map<String, Object> editParams = new HashMap<String, Object>();
//		Object [] arguments = new Object[]{editParams};
//		Map<String, String> yields = new HashMap<String, String>();
//		editParams.put("plan_id", params.get("plan_id"));
//		String[] arr = params.get("yields").split(",");
//		for (String str1 : arr) {
//			String[] str2 = str1.split("=");
//			yields.put(str2[0], str2[1]);
//		}
//		editParams.put("yields", yields);
//		String res = HproseClinetService.synCall(APIConstants.PPMSI_EDITPLANDETAILYIELD, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
//		JSONObject json = new JSONObject();
//		if("success".equals(res)){
//			json.put("error", 1);
//			json.put("msg", res);
//		}else{
//			json.put("error", -1);
//			json.put("msg", res);
//		}
//		renderJSON(json);
//	}
//	public static void upload(File myfile){
//		List list = BatchImport.getAllByExcel(myfile); 
//		for (int i = 0; i < list.size(); i++) {
//			Map<String, Object> map = (Map) list.get(i);
//			Map<String,Object> paramMap = new HashMap<String, Object>();
//			paramMap.put("machine_code", map.get("003"));
//			paramMap.put("standard_yield", map.get("006"));
//			paramMap.put("pcs_standard_yield", map.get("007"));
//			paramMap.put("auto_yield", map.get("010"));
//			paramMap.put("real_yield", map.get("011"));
//			paramMap.put("good_yield", map.get("013"));
//			paramMap.put("bad_yield", map.get("014"));
//			paramMap.put("customer_id",  UserBis.currUser());
//			Object[] arguments = new Object[]{paramMap};
// 			String res = HproseClinetService.synCall(APIConstants.MMI_ADDMACHINEYIELD, arguments, APIConstants.CUSTOMER_HOST, APIConstants.CUSTOMER_PORT);
//		}
//		index();
//	}
//	public static void download(){
//		File file = DownloadUtils.getPrUsersTemplet("模板生产报表.xls");
//		renderBinary(file);
//	}
}
